/**
 * 
 */
package com.jushu.storbox.util;

import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Link access code util class
 */
public class LinkAccessCodeUtil {

	private static final String NUMBERS = "0123456789";
	private static final String CHARS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
	private static final String OTHERS = "!@#$^&*-+.";

	/**
	 * Get random num
	 * 
	 * @param min
	 * @param max
	 * @return
	 */
	private static int getRandomNum(int min, int max) {
		Random random = new Random();
		int num = Math.abs(random.nextInt(max)) % (max - min + 1) + min;
		return num;
	}

	/**
	 * @param number
	 * @param charStr
	 * @param other
	 * @return
	 */
	private static char getRandomChar(boolean number, boolean charStr,
			boolean other) {
		StringBuffer charSet = new StringBuffer("");
		if (number) {
			charSet.append(NUMBERS);
		}
		if (charStr) {
			charSet.append(CHARS);
		}
		if (other) {
			charSet.append(OTHERS);
		}
		return charSet.toString().charAt(getRandomNum(0, charSet.length() - 1));
	}

	/**
	 * get complex access code
	 * 
	 * @param length
	 * @return
	 */
	public static String getAccessCode(int length) {
		StringBuffer buffer = new StringBuffer();
		buffer.append(getRandomChar(true, false, false));
		buffer.append(getRandomChar(false, true, false));
		buffer.append(getRandomChar(false, false, true));

		for (int i = 3; i < length; i++) {
			buffer.append(getRandomChar(true, true, true));
		}
		char[] charArray = buffer.toString().toCharArray();
		for (int i = 0; i < 50; i++) {
			int idx1 = getRandomNum(0, length - 1);
			int idx2 = getRandomNum(0, length - 1);
			if (idx1 == idx2) {
				continue;
			}
			char temp = charArray[idx1];
			charArray[idx1] = charArray[idx2];
			charArray[idx2] = temp;
		}
		return String.valueOf(charArray);
	}

	/**
	 * validate simple access code
	 * @param accessCode
	 * @return
	 */
	public static boolean isValidAccessCode(String accessCode) {
		Pattern pattern = Pattern.compile("[a-zA-Z0-9]{1,20}");
		Matcher matcher = pattern.matcher(accessCode);
		if (matcher.matches()) {
			return true;
		} else {
			return false;
		}

	}

}
